#!/usr/bin/env python

import sys
import os.path
 
try:
   import json as simplejson
except:
   import simplejson  # http://undefined.org/python/#simplejson
from twitterbot import *
 
import urllib
import pickle
 
USER_LIST_FILE = 'tweetback.pck'

#Post Feed
from time import strftime
import sqlite3

import feedparser  #available at feedparser.org

DATABASE = 'tweets.sqlite'
 
#read stored list of twitter users that have been responded to already in a file
try:
    f = open(USER_LIST_FILE, 'r')
    user_list = pickle.load(f)
except:
    user_list = []
 
def search_results(query):
    url = 'http://search.twitter.com/search.json?lang=en&q=' + '+'.join(query.split())
    return simplejson.load(urllib.urlopen(url))


class TwitterFollower(TwitterBot): 
	def do_follow(self):
		debug("In do_follow:")
		self.tweet_follow('robot')

	def do_unfollow(self):
		debug("In do_unfollow:")
		friends = self.twitter.friends(id='ids')
		followers = self.twitter.followers(id='ids')

    		try:
        		for friend in friends:
            			if friend not in followers:
            				self.twitter.friendships.destroy(id=friend)
            				print "^^\" Okay! I've stopped following %s." %(friend)
    		except:
        		print 'Failed to post update. may have gone over the twitter API limit.. please wait and try again'

	def do_jobs(self):
		self.sched.add_task((SchedTask(self.do_follow, 1800)))
		self.sched.add_task((SchedTask(self.do_unfollow, 48*3600)))
		#self.sched.add_task((SchedTask(self.tweet_rss, 3600)))

	def tweet_follow(self, query):
    		results = search_results(query)
 
    		try:
        		for result in results['results']:
            			if result['from_user'] not in user_list:
					self.follow(result['from_user'])
 
                			user_list.append(result['from_user'])
    		except:
        		print 'Failed to post update. may have gone over the twitter API limit.. please wait and try again'
 
   		 #write the user_list to disk
    		f = open(USER_LIST_FILE, 'w')
    		pickle.dump(user_list, f)

	#Post Feed to Twitter
	def print_stats(self):
		debug("In print_stats:")

		conn = sqlite3.connect(DATABASE)
		conn.row_factory = sqlite3.Row
		c = conn.cursor()

		#b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)
 
		c.execute('SELECT title, url, short_url from RSSContent')
		all_links = c.fetchall()

		for row in all_links:

			short_url = row['short_url']

			if short_url is None:
				#short_url = b.shorten(row['url'])
				short_url = self.bitly.shorten(row['url'])
				c.execute('UPDATE RSSContent SET `short_url`=? WHERE `url`=?',(short_url,row['url']))


			#stats = b.stats(short_url)
			stats = self.bitly.stats(short_url)
			print "%s - User clicks %s, total clicks: %s" % (row['title'], stats.user_clicks,stats.total_clicks)

		conn.commit()

	def tweet_rss(self):
		debug("In tweet_rss:")
		
		url = 'http://feeds.feedburner.com/Vigoth'

		conn = sqlite3.connect(DATABASE)
		conn.row_factory = sqlite3.Row
		c = conn.cursor()

		#create the table if it doesn't exist
		c.execute('CREATE TABLE IF NOT EXISTS RSSContent (`url`, `title`, `dateAdded`, `content`, `short_url`)')

		#api = twitter.Api(username=TWITTER_USER, password=TWITTER_PASSWORD)
		#b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)

		d = feedparser.parse(url)

		for entry in d.entries:

			#check for duplicates
			c.execute('select * from RSSContent where url=?', (entry.link,))
			if not c.fetchall():

				tweet_text = "%s - %s" % (entry.title, "entry.summary")

				#shortened_link = b.shorten(entry.link)
				shortened_link = self.bitly.shorten(entry.link)

				t = (entry.link, entry.title, strftime("%Y-%m-%d %H:%M:%S", entry.updated_parsed), "entry.summary", shortened_link)
				c.execute('insert into RSSContent (`url`, `title`,`dateAdded`, `content`, `short_url`) values (?,?,?,?,?)', t)
				print "%s.. %s" % (tweet_text[:115], shortened_link)

				#api.PostUpdate("%s.. %s" % (tweet_text[:115], shortened_link))
				status_text = "%s.. %s" % (tweet_text[:115], shortened_link)
				#print status_text
				self.twitter.statuses.update(status=status_text)
 
		conn.commit()
		self.print_stats()

 
def main():
    configFilename = "twitterbot.ini"
    if (sys.argv[1:]):
        configFilename = sys.argv[1]
        
    try:
        if not os.path.exists(configFilename):
            raise Exception()
        load_config(configFilename)
    except Exception, e:
        print >> sys.stderr, "Error while loading ini file %s" %(
            configFilename)
        print >> sys.stderr, e
        print >> sys.stderr, __doc__
        sys.exit(1)

    bot = TwitterFollower(configFilename)
    bot.do_jobs()
    return bot.run()
    #return bot.do_follow()
    #return bot.do_unfollow()
    #return bot.tweet_rss()

if __name__ == "__main__":
	main()

